package tyk.Servlet;


import org.apache.commons.io.IOUtils;
import tyk.Service.BookService;
import tyk.pojo.AccountPage;
import tyk.pojo.Book;
import tyk.pojo.Page;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/***
 *@title $NAME
 *@description <TODO description class purpose>
 *@author Tang'ya'kang
 *@VERSION 1.0.0
 *@CREATE 2023/5/11 15:21
 **/
public class BookServlet extends HttpServlet {
    public void SelectEvery(HttpServletRequest request,HttpServletResponse response){
        BookService bookService = new BookService();    //一次性将所有图书信息展示出来，考虑后期图书数量可能太多，所以将其淘汰
        List<Book> list=bookService.SelectEvery();
        request.setAttribute("books",list);
        try {
            request.getRequestDispatcher("./BookManage.jsp").forward(request,response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void PageByPageNo(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String user_name=request.getParameter("user_name");
        Integer merchant_id= Integer.valueOf(request.getParameter("merchant_id"));
        BookService bookService = new BookService();    //一次性将所有图书信息分页展示出来
        Integer Page= Integer.valueOf(request.getParameter("Page"));
        Integer PageTotal,Count;
        List<Book> list;
        if(user_name.equals("root")) Count=bookService.SelectEvery().size();
        else Count=bookService.SelectEvery(merchant_id).size();
        PageTotal=Count/12;
        if(Count%12!=0) PageTotal++;
        if(Page<1) Page=1;
        else if(Page>PageTotal) Page=PageTotal;
        AccountPage accountPage=new AccountPage(PageTotal,Page,Count);
        System.out.println(accountPage);
        if(user_name.equals("root")) list=bookService.PageByPageNo(Page);
        else list=bookService.PageByPageNoMerchant_id(Page,merchant_id);
        request.setAttribute("books",list);
        request.setAttribute("AccountPage",accountPage);
        request.setAttribute("url","./manage/bookServlet?action=PageByPageNo&user_name="+user_name+"&merchant_id="+merchant_id+"&Page=");
        request.getRequestDispatcher("./BookManage.jsp").forward(request,response);
    }
    public void AddBook(HttpServletRequest request,HttpServletResponse response) throws SQLException, ServletException, IOException, IllegalAccessException, NoSuchFieldException, InstantiationException {
        Integer count= Integer.valueOf(request.getParameter("count"));
        String user_name=request.getParameter("user_name");
        BookService bookService = new BookService();

        Integer PageTocal= Integer.valueOf(request.getParameter("PageTotal"));

        String bookname=request.getParameter("bookname");
        String username=request.getParameter("username");
        Integer merchant_id= Integer.valueOf(request.getParameter("merchant_id"));

        int sales= Integer.parseInt(request.getParameter("sales"));
        int stock= Integer.parseInt(request.getParameter("stock"));

        double priceTemp= Double.parseDouble(request.getParameter("price"));

        BigDecimal price=new BigDecimal(priceTemp);
        // 获取文件上传对象
        Part bookImagePart = request.getPart("bookImage");
        // 使用 UUID 生成唯一文件名，并添加文件扩展名
        String uuid = UUID.randomUUID().toString();
        String newFileName = uuid + ".jpg";

        // 设置文件保存路径(保存到 "/uploads" 目录下)
        String uploadPath = request.getServletContext().getRealPath("/uploads");

        // 检查上传目录是否存在，如果不存在，则创建。
        File uploadDir = new File(uploadPath);
        System.out.println(uploadDir);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        Book book = new Book(bookname,username,price,sales,stock,merchant_id);
        Integer maxcount=bookService.SelectMaxcount(merchant_id);
        if(maxcount>count) {
            if (bookImagePart != null && bookImagePart.getSize() > 0) book.setimg_path(newFileName);
            bookService.add(book.getName(),book.getPrice(),book.getAuthor(),book.getSales(),book.getStock(),book.getMerchant_id(),book.getimg_path());
            if (bookImagePart != null && bookImagePart.getSize() > 0){
                    InputStream input = bookImagePart.getInputStream();
                    FileOutputStream output = new FileOutputStream(new File(uploadPath, newFileName));
                    IOUtils.copy(input, output);
                    IOUtils.closeQuietly(input);
                    IOUtils.closeQuietly(output);
                }
        }
        else request.getRequestDispatcher("/manage/MaxCount.html").forward(request,response);
        request.getRequestDispatcher("/manage/bookServlet?action=PageByPageNo&user_name="+user_name+"&merchant_id="+merchant_id+"&Page="+PageTocal).forward(request,response);
    }

    public void DeleteBook(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String user_name=request.getParameter("user_name");
        Integer merchant_id= Integer.valueOf(request.getParameter("merchant_id"));
        int id= Integer.parseInt(request.getParameter("id"));
        String Page=request.getParameter("Page");
        BookService bookService=new BookService();
        bookService.DeleteById(id);
        request.getRequestDispatcher("/manage/bookServlet?action=PageByPageNo&user_name="+user_name+"&merchant_id="+merchant_id+"&Page="+Page).forward(request,response);
    }
    public void EditById(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String Page=request.getParameter("Page");
        Integer id= Integer.parseInt(request.getParameter("id"));
        String user_name=request.getParameter("user_name");
        Integer merchant_id= Integer.valueOf(request.getParameter("merchant_id"));
        BookService bookService=new BookService();
        List<Book> list=new ArrayList<>();
        list=bookService.SelectById(id);
        Book book=list.get(0);
        request.setAttribute("book",book);
        request.getRequestDispatcher("/manage/EditBook.jsp?Page="+Page+"&user_name="+user_name+"&merchant_id="+merchant_id).forward(request,response);
    }

    public void EditBook(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String user_name=request.getParameter("user_name");
        Integer merchant_id= Integer.valueOf(request.getParameter("merchant_id"));
        int id= Integer.parseInt(request.getParameter("id"));
        String name=request.getParameter("name");
        String author=request.getParameter("author");
        int sales= Integer.parseInt(request.getParameter("sales"));
        int stock= Integer.parseInt(request.getParameter("stock"));
        double priceTemp= Double.parseDouble(request.getParameter("price"));
        BigDecimal price=new BigDecimal(priceTemp);
        BookService bookService=new BookService();
        Book book=new Book(name,author,price,sales,stock,null);
        book.setId(id);
        bookService.EditBook(book);
        String Page=request.getParameter("Page");
        request.getRequestDispatcher("/manage/bookServlet?action=PageByPageNo&user_name="+user_name+"&merchant_id="+merchant_id+"&Page="+Page).forward(request,response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String hidden=request.getParameter("action");
        try {
            Method method = this.getClass().getDeclaredMethod(hidden,HttpServletRequest.class,HttpServletResponse.class);
            method.invoke(this,request,response);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String hidden=request.getParameter("action");
        try {
            Method method = this.getClass().getDeclaredMethod(hidden,HttpServletRequest.class,HttpServletResponse.class);
            method.invoke(this,request,response);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
